package com.study.scheduled.controller;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @description:
 * @author: Leo
 * @createDate: 2020/4/19
 * @version: 1.0
 */
//@EnableScheduling
//@Configuration
public class DynamicScheduleTask implements SchedulingConfigurer
{
    @Autowired      //注入mapper
    @SuppressWarnings("all")
    CronMapper cronMapper;

    @Mapper
    public interface CronMapper
    {
        @Select("select cron from cron limit 1")
        String getCron();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar)
    {
        scheduledTaskRegistrar.addTriggerTask(() -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                triggerContext ->
                {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    if (StringUtils.isEmpty(cron))
                    {
                        System.out.println("发现为空");
                        //new DynamicScheduleTask().configureTasks(scheduledTaskRegistrar);
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });
    }
}
